
package com.jf.cloud.seckill.listener;

import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.vo.ShopCartOrderMergerVO;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.seckill.service.SeckillOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;


/**
 * 秒杀提交订单事务监听
 * @author zz
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "seckillOrderCreateTemplate",maximumPoolSize = 20)
public class SeckillOrderCreateTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object obj) {
        ShopCartOrderMergerVO mergerOrder = Json.parseObject((byte[])msg.getPayload(), ShopCartOrderMergerVO.class);
        try {
            seckillOrderService.submit(mergerOrder);
        }catch (LuckException e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        ShopCartOrderMergerVO mergerOrder = Json.parseObject((byte[])msg.getPayload(), ShopCartOrderMergerVO.class);
        Long orderId = mergerOrder.getShopCartOrders().get(0).getOrderId();
        if (seckillOrderService.orderSaveSuccess(orderId)) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
